package util

import (
	"fmt"
	"github.com/shopspring/decimal"
	"regexp"
	"strings"
)

type ByteSize float64
type FileSize string

const (
	_            = iota
	_KB ByteSize = 1 << (10 * iota)
	_MB
	_GB
	_TB
	_PB
	_EB
	_ZB
	_YB
)
const REG_PATTERN = ""

func (fileSize FileSize) ToByteSize() decimal.Decimal {
	upperFileSize := strings.ToUpper(string(fileSize))
	reg := regexp.MustCompile(`(\d+(\.\d+)?)(KB|MB|GB|TB|PB|EB|ZB|YB)`)
	res := reg.FindAllStringSubmatch(string(upperFileSize), -1)
	fmt.Println(res)
	size, _ := decimal.NewFromString(res[0][1])
	switch res[0][3] {
	case "KB":
		return size.Mul(decimal.NewFromFloat(float64(_KB)))
	case "MB":
		return size.Mul(decimal.NewFromFloat(float64(_MB)))
	case "GB":
		return size.Mul(decimal.NewFromFloat(float64(_GB)))
	case "TB":
		return size.Mul(decimal.NewFromFloat(float64(_TB)))
	case "PB":
		return size.Mul(decimal.NewFromFloat(float64(_PB)))
	case "EB":
		return size.Mul(decimal.NewFromFloat(float64(_EB)))
	case "ZB":
		return size.Mul(decimal.NewFromFloat(float64(_ZB)))
	case "YB":
		return size.Mul(decimal.NewFromFloat(float64(_YB)))
	}
	return decimal.Zero
}

// 字节的单位转换 保留两位小数
func (b ByteSize) ToString() string {
	switch {
	case b >= _YB:
		return fmt.Sprintf("%.2fYB", b/_YB)
	case b >= _ZB:
		return fmt.Sprintf("%.2fZB", b/_ZB)
	case b >= _EB:
		return fmt.Sprintf("%.2fEB", b/_EB)
	case b >= _PB:
		return fmt.Sprintf("%.2fPB", b/_PB)
	case b >= _TB:
		return fmt.Sprintf("%.2fTB", b/_TB)
	case b >= _GB:
		return fmt.Sprintf("%.2fGB", b/_GB)
	case b >= _MB:
		return fmt.Sprintf("%.2fMB", b/_MB)
	case b >= _KB:
		return fmt.Sprintf("%.2fKB", b/_KB)
	}
	return fmt.Sprintf("%.2fB", b)
}
